package ${package};

import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.tinygroup.application.AbstractApplicationProcessor;
import org.tinygroup.beancontainer.BeanContainerFactory;
import org.tinygroup.commons.tools.Resources;
import org.tinygroup.config.util.ConfigurationUtil;
import org.tinygroup.logger.LogLevel;
import org.tinygroup.logger.Logger;
import org.tinygroup.logger.LoggerFactory;
import org.tinygroup.xmlparser.node.XmlNode;

/**
 * 初始化数据源相关表信息
 * @author yancheng11334
 *
 */
public class InitDataSourceProcessor extends AbstractApplicationProcessor {

	private static final Logger LOGGER = LoggerFactory.getLogger(InitDataSourceProcessor.class);
	
	private XmlNode applicationConfig;
	private XmlNode componentConfig;
	
	

	public void start() {
		LOGGER.logMessage(LogLevel.INFO, "开始初始化数据源表...");
		try{
			 String beanName = ConfigurationUtil.getConfigurationManager().getConfiguration("customBean");
			 DataSource dataSource = BeanContainerFactory.getBeanContainer(
	                    getClass().getClassLoader()).getBean(beanName);
			 initTable(dataSource);
		}catch(Exception e){
			LOGGER.error("初始化数据源表发生异常:", e);
		}
		LOGGER.logMessage(LogLevel.INFO, "初始化数据源表完毕!");
	}
	
	private void initTable(DataSource dataSource) throws Exception{
		Connection conn = null;
		try{
			conn = dataSource.getConnection();
			SqlScriptRunner runner = new SqlScriptRunner(conn, false, false);
	        // 设置字符集
	        Resources.setCharset(Charset.forName("utf-8"));
	        // 加载sql脚本并执行
	        runner.runScript(Resources.getResourceAsReader("initdatasource.sql"));
		}finally{
			if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                	LOGGER.error("关闭连接发生异常:", e);
                }
            }
		}
	}

	
	public void stop() {
		
	}

	public String getApplicationNodePath() {
        return "/application/initdatasource";
    }

    public String getComponentConfigPath() {
        return "/initdatasources.config.xml";
    }


    public void config(XmlNode applicationConfig, XmlNode componentConfig) {
        this.applicationConfig = applicationConfig;
        this.componentConfig = componentConfig;
    }

    public XmlNode getComponentConfig() {
        return componentConfig;
    }

    public XmlNode getApplicationConfig() {
        return applicationConfig;
    }

    public int getOrder() {
        return 0;
    }


}
